package com.ken.apollo.controller;


import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.IdUtil;
import com.ken.apollo.commons.result.R;
import com.ken.apollo.service.ImageProcessingService;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;

@RestController
@RequestMapping("/api/file")
@Slf4j
public class FileController {

    @Value("${upload.path}")
    private String uploadPath;
    
    @Autowired
    private ImageProcessingService imageProcessingService;

    /**
     * 上传文件
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R<String> uploadFile(@RequestParam("file") MultipartFile file){
        //使用UUID作为文件名称
        String fileName = IdUtil.fastSimpleUUID();

        File files = new File(uploadPath);
        if(!files.exists()){
            files.mkdirs();
        }
        files = new File(files, fileName);

        try (
                InputStream in = file.getInputStream();
                OutputStream out = new FileOutputStream(files);
        ){
            IoUtil.copy(in, out);
        } catch (IOException e) {
            log.error("upload file error: 上传文件失败！" + file.getOriginalFilename(), e);
            return R.fail("上传失败！" + e.getMessage());
        }

        //返回上传的绝对路径
        return R.success(fileName);
    }

    /**
     * 判断是否上传
     * @return
     */
    @GetMapping("/isupload")
    public R<Boolean> isUpload(String filename){
        File files = new File(uploadPath, filename);
        return R.success(files.exists());
    }

    /**
     * 获取图片文件获取
     */
    @GetMapping("/get")
    public R get(String filename, HttpServletResponse response){
        File files = new File(uploadPath, filename);
        if (!files.exists()){
            return R.fail("文件不存在");
        }

        //设置图片的类型
        response.setHeader("Content-Type", "image/jpeg");
//        response.setHeader("Content-Disposition", "attachment;filename=" + filename);
        try (FileInputStream inputStream = new FileInputStream(files);
             ServletOutputStream outputStream = response.getOutputStream()){
            IoUtil.copy(inputStream, outputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    /**
     * 调整图片分辨率
     * @param filename 原文件名
     * @param width 目标宽度(可选，默认1920)
     * @param height 目标高度(可选，默认1080)
     * @param quality 质量(可选，默认0.9)
     * @return 新文件名
     */
    @PostMapping("/resize")
    public R<String> resizeImage(@RequestParam("filename") String filename,
                                @RequestParam(value = "width", defaultValue = "1920") int width,
                                @RequestParam(value = "height", defaultValue = "1080") int height,
                                @RequestParam(value = "quality", defaultValue = "0.9") float quality) {
        try {
            String newFilename = imageProcessingService.resizeImage(filename, width, height, quality);
            return R.success(newFilename, "图片处理成功");
        } catch (Exception e) {
            log.error("图片处理失败: {}", filename, e);
            return R.fail("图片处理失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取图片信息
     * @param filename 文件名
     * @return 图片信息
     */
    @GetMapping("/info")
    public R<ImageProcessingService.ImageInfo> getImageInfo(@RequestParam("filename") String filename) {
        try {
            ImageProcessingService.ImageInfo imageInfo = imageProcessingService.getImageInfo(filename);
            if (imageInfo == null) {
                return R.fail("图片不存在或无法读取");
            }
            return R.success(imageInfo);
        } catch (Exception e) {
            log.error("获取图片信息失败: {}", filename, e);
            return R.fail("获取图片信息失败: " + e.getMessage());
        }
    }
    
    /**
     * 批量处理图片（提升为高清）
     * @param filename 原文件名
     * @return 处理结果
     */
    @PostMapping("/enhance")
    public R<String> enhanceImage(@RequestParam("filename") String filename) {
        try {
            // 获取原图片信息
            ImageProcessingService.ImageInfo originalInfo = imageProcessingService.getImageInfo(filename);
            if (originalInfo == null) {
                return R.fail("原图片不存在");
            }
            
            // 计算增强后的尺寸（最大提升到2倍，但不超过4K）
            int newWidth = Math.min(originalInfo.getWidth() * 2, 3840);
            int newHeight = Math.min(originalInfo.getHeight() * 2, 2160);
            
            // 如果原图已经很大，则使用高质量重新编码
            if (originalInfo.getWidth() >= 1920) {
                newWidth = originalInfo.getWidth();
                newHeight = originalInfo.getHeight();
            }
            
            String enhancedFilename = imageProcessingService.resizeImage(filename, newWidth, newHeight, 0.95f);
            return R.success(enhancedFilename, "图片增强完成");
        } catch (Exception e) {
            log.error("图片增强失败: {}", filename, e);
            return R.fail("图片增强失败: " + e.getMessage());
        }
    }
}
